package com.eas.task.imports;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.eas.task.imports.datasource.DsConfig;
import com.eas.task.imports.datasource.DsFactory;
import com.eas.task.imports.job.ImportDataJob;
import com.eas.task.imports.status.JobStatus;
import com.eas.task.imports.status.ManagerStatus;

public class TaskManager implements ApplicationContextAware {

    private ManagerStatus status;

    private DataSource ds;

    private DsConfig config;

    private Map<String, JobStatus> jobMap;

    private ExecutorService executor;

    private ApplicationContext applicationContext;

    public void init() {
        status = ManagerStatus.IDLE;
        jobMap = new HashMap<String, JobStatus>();

        executor = Executors.newFixedThreadPool(1);
    }

    public synchronized void startCreate() {
        status = ManagerStatus.CREATE;
    }

    public synchronized void cancelCreate() {
        ds = null;
        config = null;
        status = ManagerStatus.IDLE;
    }

    public synchronized void createDatasource(DsConfig config) {
        if (status == ManagerStatus.CREATE) {
            this.config = config;
            ds = DsFactory.create(config);
            status = ManagerStatus.CONFIG;
        }
    }

    public synchronized void submitJob(ImportDataJob job) {
        if (job != null) {
            job.setApplicationContext(applicationContext);
            jobMap.put(job.getUuid(), job.getStatus());

            executor.submit(job);
        }
    }

    public synchronized void removeJob(String uuid) {
        jobMap.remove(uuid);
    }

    public ManagerStatus getStatus() {
        return status;
    }

    public Collection<JobStatus> getJobStatus() {
        return jobMap.values();
    }

    public DataSource getDatasource() {
        return ds;
    }

    public DsConfig getDsConfig() {
        return config;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
